<template>
	<div class="zBox">
		<div class="qjButtonBox">
			<div class="qjBut" @click="approval">
				<el-icon style="vertical-align: middle" :color="'#ffffff'"><Edit /></el-icon>
				<span style="vertical-align: middle;margin-left: 8px;">加班申请</span>
			</div>
		</div>
		<el-table class="qjTable" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" stripe>
			<el-table-column label="加班项目" align="center" prop="projectName" />
			<el-table-column label="提交时间" align="center" prop="createTime" />
			<el-table-column label="加班时长" align="center" prop="workHour" />
			<el-table-column label="状态" align="center">
				<template #default="scope">
					<div class="ztbox">
						<div class="dian" :style="{ background: qjzt[scope.row.status].color }"></div>
						<span :style="{ color: qjzt[scope.row.status].color }">{{ qjzt[scope.row.status].label }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center">
				<template #default="scope">
					<div class="czan">
						<div v-if="scope.row.status == 0 && scope.row.isEdit" class="czBut bjckdj" @click="edit(scope.row.overworkId)">编辑</div>
						<div v-if="scope.row.status == 0 && scope.row.isEdit" class="czBut sc" @click="delForm(scope.row)">删除</div>
						<div class="czBut bjckdj" @click="detail(scope.row.overworkId)">查看</div>
					</div>
				</template>
			</el-table-column>
		</el-table>
		<pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
		<!-- 加班申请弹框 -->
		<el-dialog class="overDialog" v-model="overDialogVisible" title="加班申请" top="12vh" width="38.5%" :close-on-click-modal="false">
			<el-form ref="ruleFormRef" :model="overForm" :rules="overRules" label-width="83px">
				<div class="left">
					<el-form-item label="所属项目" prop="projectId">
						<el-select style="width: 83%;" filterable v-model="overForm.projectId" placeholder="请选择(可搜索)">
							<el-option v-for="item in project_List" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="开始时间" prop="startTime">
						<el-date-picker
							style="width: 83%;"
							value-format="YYYY-MM-DD HH:mm"
							format="YYYY-MM-DD HH:mm"
							v-model="overForm.startTime"
							type="datetime"
							placeholder="请选择日期时间"
							@change="startTimeChange"
						/>
					</el-form-item>
					<el-form-item label="结束时间" prop="endTime">
						<el-date-picker
							style="width: 83%;"
							value-format="YYYY-MM-DD HH:mm"
							format="YYYY-MM-DD HH:mm"
							v-model="overForm.endTime"
							type="datetime"
							placeholder="请选择日期时间"
							@change="endTimeChange"
						/>
					</el-form-item>
					<el-form-item label="加班时长" prop="workHour">
						<el-input style="width: 83%;" v-model="overForm.workHour" placeholder="0">
							<template #append>
								小时
							</template>
						</el-input>
					</el-form-item>
					<el-form-item label="加班事由:" prop="reason"><el-input style="width: 83%;" type="textarea" v-model="overForm.reason" rows="3"></el-input></el-form-item>
				</div>
				<div class="right">
					<el-form-item class="spr" label="审核人" prop="approveId">
						<el-select style="width: 100%;" v-model="overForm.approveId" @change="appoversChange" filterable allow-create default-first-option placeholder="请选择人员">
							<el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
								<div class="userOption">
									<img :src="item.headImg" alt="" />
									<span>{{ item.label }}</span>
								</div>
							</el-option>
						</el-select>
					</el-form-item>
					<div v-if="sprData.label" class="spBox sxm">
						<img :src="sprData.headImg" />
						<p>{{ sprData.label }}</p>
					</div>
					<el-form-item class="csr" label="抄送人" prop="copyIds">
						<el-select
							style="width: 100%;"
							v-model="overForm.copyIds"
							multiple
							@change="copyChange"
							filterable
							allow-create
							default-first-option
							placeholder="请选择人员"
						>
							<el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
								<div class="userOption">
									<img :src="item.headImg" alt="" />
									<span>{{ item.label }}</span>
								</div>
							</el-option>
						</el-select>
					</el-form-item>
					<div v-if="csrData.length > 0" class="csrBox">
						<div v-for="(item, index) in csrData" class="spBox2">
							<img :src="item.headImg" />
							<p>{{ item.label }}</p>
						</div>
					</div>
				</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="overDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog class="overDialog" v-model="detailDialogVisible" title="加班信息" top="12vh" width="45%">
			<table class="mailTable">
				<tr>
					<td class="column ">姓名</td>
					<td class="nrkd">{{ workDetail.createBy }}</td>
					<td class="column ">所属项目</td>
					<td class="nrkd">{{ workDetail.projectName }}</td>
				</tr>
				<tr>
					<td class="column">提交时间</td>
					<td class="nrkd">{{ workDetail.createTime }}</td>
					<td class="column ">加班时长</td>
					<td class="nrkd">{{ workDetail.workHour }}小时</td>
				</tr>
				<tr>
					<td class="column">开始时间</td>
					<td class="nrkd">{{ workDetail.startTime }}</td>
					<td class="column ">结束时间</td>
					<td class="nrkd">{{ workDetail.endTime }}</td>
				</tr>

				<tr>
					<td class="column ">抄送人</td>
					<td class="nrkd">{{ workDetail.copyNames }}</td>
					<td class="column ">加班事由</td>
					<td class="nrkd lineHeight">{{ workDetail.reason }}</td>
				</tr>
				<tr>
					<td class="column">打卡记录</td>
					<td class="nrkd li2Height " colspan="3">
						<div class="dkJl">
							<div v-if="attendanceRecordList" class="red" v-for="(item, index) in attendanceRecordList">
								{{ '打卡时间' + (index + 1) + ':' + '\xa0\xa0\xa0' + item.userCheckTime }}
							</div>
							<div v-else id="">暂无记录</div>
						</div>
					</td>
				</tr>

				<tr>
					<td class="column">审核进度</td>
					<td class="nrkd lineHeight" colspan="3">
						<p class="jdbox" style="display: flex;" v-for="(item, index) in auditList">
							<span class="spzt" :class="{ ytg: item.status == 2, btg: item.status == 1, dsh: item.status == 0 }"></span>
							<span class="xuLine" style="position: absolute;width: 2px;height: 20px;border: 1px dashed #ccc;"></span>
							<span>{{ item.createBy + '\xa0\xa0\xa0' + (item.status == 0 ? '待审核' : item.updateTime) + '\xa0\xa0\xa0' + (item.reason ? item.reason : '') }}</span>
						</p>
					</td>
				</tr>
			</table>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import {getUserOptions,getOverworkList,getProjectSelect,addOverWork,deleteOverwork,getOverWorkDetail,updateOverwork,getAuditList} from '@/api/hkd';
import useUserStore from '@/store/modules/user';
import moment from 'moment';
import {nextTick} from 'vue';
import headurl from '@/assets/images/head.png';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const tableList = ref([]);
const total = ref(0);
const loading = ref(true);
const userId = ref(useUserStore().userId);
const overDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const project_List = ref([]);
const checked = ref(true);
const { proxy } = getCurrentInstance();

const auditList =ref([]);
const attendanceRecordList =ref([]);

const userOptions = ref([]);
const csrData = ref([]);
const overWorkHour = ref(0);
const offsetTime = ref(0);
const print = ref(null);
const sprData = ref({
	headImg: '',
	label: ''
})
const workDetail = ref({})
const qjzt = ref({
	0: { color: '#FA6400', label: '待审核',img:'dsh' },
	1: { color: '#BE1A21', label: '未通过',img:'btg' },
	2: { color: '#1AC45F', label: '通过',img:'ok' }
});
const checkAbsenceDuration = (rule, value, callback) => {
	if (!value) {
		return callback(new Error('输入加班时长'));
	} else {
		const reg = /^(([1-9][0-9]*)|0)(\.(5|0))?$/;
		if (reg.test(value)) {
			callback();
		} else {
			return callback(new Error('请输入0.5的倍数！'));
		}
	}
};

const data = reactive({
	overForm:{
		startTime: '',
		endTime: '',
		projectId: '',
		reason: '',
		approveId: '',
		copyIds: [],
	},
	xjForm:{
		reportBackDuration: '',
		reportBackTime: '',
		reportBackReason: '',
	},
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		type:'my'
	},
	xjRules:{
		workHour: [
			{
				required: true,
				message: '输入加班时长',
				trigger: 'blur'
			},
			{
				validator: checkAbsenceDuration,
				trigger: 'blur'
			}
		],
		reportBackTime: [
			{
				required: true,
				message: '请选择销假时间',
				trigger: 'blur'
			}
		],
		reportBackReason: [
			{
				required: true,
				message: '请输入备注',
				trigger: 'blur'
			}
		]
	}
});

const makeRange = (start: number, end: number) => {
  const result: number[] = []
  for (let i = start; i <= end; i++) {
    result.push(i)
  }
  return result
}
const disabledHours = () => {
  return makeRange(0, 7).concat(makeRange(19,23))
}
const disabledMinutes = (hour: number) => {
  if (hour === 8 ) {
    return makeRange(0,29)
  }
  if (hour === 11 ) {
    return makeRange(31,59)
  }
  if (hour === 18 ) {
    return makeRange(1,59)
  }
  // if (hour === 18) {
  //   return makeRange(00, 59)
  // }
}
const disabledSeconds = (hour: number, minute: number) => {
  // if (hour === 8 && minute === 30) {
  //   return makeRange(1, 59)
  // }
}
const { queryParams,overForm,xjRules,xjForm } = toRefs(data);
const overRules = reactive({
	workHour: [
		{
			required: true,
			message: '输入加班时长',
			trigger: 'blur'
		},
		{
			validator: checkAbsenceDuration,
			trigger: 'blur'
		}
	],
	projectId: [
		{
			required: true,
			message: '请选择所属项目',
			trigger: 'blur'
		}
	],
	endTime: [
		{
			required: true,
			message: '请选择结束时间',
			trigger: 'blur'
		}
	],
	startTime: [
		{
			required: true,
			message: '请选择开始时间',
			trigger: 'blur'
		}
	],
	reason: [
		{
			required: true,
			message: '输入加班原因',
			trigger: 'blur'
		}
	],
	approveId: [
		{
			required: true,
			message: '请选择审核人',
			trigger: 'change'
		}
	],
	copyIds: [
		{
			required: true,
			message: '请选择抄送人',
			trigger: 'blur'
		}
	],
});

// watch(overForm.value.startTime, (newValue, oldValue) => {
//   console.log('值发生了变更', newValue, oldValue);
// });

onMounted(() => {
});
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
		let form = JSON.parse(JSON.stringify(overForm.value ))
		form.applyId = userId.value
		form.copyIds = form.copyIds.toString();
		if(form.overworkId){
			updateOverwork(form).then(res=>{
				if(res.code =='200'){
					   ElMessage({ message: '申请成功！', type: 'success', duration: 1 * 1000 })
					   getList()
					   overDialogVisible.value = false
				}else{
					ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
				}
			})
		}else{
			addOverWork(form).then(res=>{
				if(res.code =='200'){
					   ElMessage({ message: '申请成功！', type: 'success', duration: 1 * 1000 })
					   getList()
					   overDialogVisible.value = false
				}else{
					ElMessage({ message: res.msg, type: 'error', duration: 1 * 1000 })
				}
			})
		}

    } else {
    }
  })
}

const delForm = (row) => {
  ElMessageBox.confirm(
  '确定删除选定的记录吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
	  deleteOverwork(row.overworkId).then(res => {
	  	if (res.code == 200) {
			ElMessage({
			  type: 'success',
			  message: '删除成功',
			});
			getList()
	  	} else {
			ElMessage({
			  type: 'warning',
			  message: res.errmsg,
			})
	  	}
	  });
    })
}
function edit(overworkId){
	overDialogVisible.value = true
	getOverWorkDetail({overworkId:overworkId}).then(res=>{
		if (res.code == 200) {
		overForm.value = res.data
		overForm.value.copyIds = res.data.copyIds.split(',')
	    // overForm.value.copyIds= overForm.value.copyIds.map(Number);
		copyChange( overForm.value.copyIds)
		appoversChange(overForm.value.approveId)
		} else {
			ElMessage({
			  type: 'warning',
			  message: res.errmsg,
			})
		}
	})
}



function detail(overworkId){
	detailDialogVisible.value = true;
	getOverWorkDetail({ overworkId: overworkId }).then(res => {
		if (res.code == 200) {
		    workDetail.value = res.data

		} else {
			ElMessage({
				type: 'warning',
				message: res.errmsg
			});
		}
	});

	getAuditList({ overworkId: overworkId }).then(res => {
		auditList.value = res.data.auditList
		attendanceRecordList.value = res.data.attendanceRecordList
	})
}






function getList() {
	loading.value = true;
	getOverworkList(queryParams.value).then(response => {
		tableList.value = response.rows;
		total.value = response.total;
		loading.value = false;
	});
}
function appoversChange(data) {
	let arr = userOptions.value.filter(item => {
		if (item.value == data) {
			return item;
		}
	});
	sprData.value = arr[0];
}
function copyChange(data) {
	csrData.value=[]
	data.map(item => {
		userOptions.value.map(item2 => {
			if (item == item2.value) {
				csrData.value.push(item2);
			}
		});
	});
}
function approval() {
	if(ruleFormRef.value){
		ruleFormRef.value.resetFields()
	}
	overForm.value.copyIds=[]
	csrData.value=[]
	userOptions.value.forEach(ele => {
		if (ele.roles.indexOf('hr') >-1 ) {
		overForm.value.copyIds.push(ele.value)
			csrData.value.push({
				headImg: ele.headImg,
				label: ele.label
			});
		}
	});
	sprData.value=[]
	overDialogVisible.value = true;

}
function getUserSelect() {
	getUserOptions({
		userId: userId.value
	}).then(res => {
		userOptions.value = res.data;
		userOptions.value.forEach(ele => {
			if (ele.headImg) {
				// debugger
				ele.headImg = import.meta.env.VITE_APP_BASE_API + ele.headImg;
			} else {
				ele.headImg = headurl;
			}
		});
		//从首页跳过来的
		if (proxy.$route.query.isSy) {
			approval()
		}

	});
}


function getProjectSelectList(){
	getProjectSelect().then(res=>{
		project_List.value =res.data
	})
}

function startTimeChange(value){
	if (overForm.value.endTime) {
		let sTime = moment(value).valueOf();
		let eTime = moment(overForm.value.endTime).valueOf();
		if (sTime > eTime) {
			ElMessage({
				message: '开始时间不能大于结束时间',
				type: 'error'
			});
			overForm.value.startTime = '';
		}else{
		}
	}
}
function endTimeChange(value){
	if (overForm.value.startTime) {
		let sTime = moment(overForm.value.startTime).valueOf();
		let eTime = moment(value).valueOf();
		if (sTime > eTime) {
			ElMessage({
				message: '开始时间不能大于结束时间',
				type: 'error'
			});
			overForm.value.endTime = '';
		}else{
		}
	}
}



getProjectSelectList()
getUserSelect();
getList();
</script>

<style lang="scss" scoped>
.qjButtonBox {
	padding: 20px 30px;
	padding-left: 0;
	padding-top: 10px;
}
.qjBut {
	background: #be1a21;
	color: #ffffff;
	width: 100px;
	text-align: center;
	border-radius: 4px;
	padding: 10px 0;
	font-size: 0.875rem;
	cursor: pointer;
}
.dialog-footer button:first-child {
	margin-right: 10px;
}
:deep(.el-form) {
	display: flex;
	.left {
		.el-input {
			height: 40px;
		}
		// height: 100px;
		border-right: 2px dashed #e5e1e1;
	}
}
.userOption {
	align-items: center;
	display: flex;
	align-items: center;
	border-radius: 50%;

	img {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		object-fit: cover;
	}

	span {
		padding: 0 1rem;
	}
}
.sxm {
	margin-top: 20px;
}
.spBox,
.spBox2 {
	display: flex;
	flex-flow: column;

	p {
		margin-top: 0;
	}
	img {
		width: 45px;
		height: 45px;
		object-fit: cover;
		border-radius: 50%;
	}
}
.spBox2 {
	margin-right: 20px;
}
:deep(.left) {
	width: 50%;
	.el-form-item {
		display: flex;
		flex-flow: column;
	}
}
:deep(.right) {
	margin-left: 50px;
	width: 42%;
	.el-form-item {
		.el-input {
			min-height: 40px;
		}
		display: flex;
		flex-flow: column;
	}
	.spr,
	.csr {
		margin-bottom: 10px;
		.el-form-item__label {
			width: 70px !important;
		}
	}
}
.csrBox {
	margin-top: 20px;
	display: flex;
	max-height: 235px;
	overflow: auto;
	display: flex;
	flex-flow: wrap;
}
.csrBox::-webkit-scrollbar {
	display: none; /* Chrome Safari */
}
:deep(.qjTable) {
	.el-table__header-wrapper,
	.el-table__fixed-header-wrapper {
		th {
			word-break: break-word;
			background-color: #f7f7f7 !important;
			color: #515a6e;
			height: 58px !important;
			font-size: 13px;
			border: none !important;
		}
	}
	.el-table__body-wrapper {
		.el-button [class*='el-icon-'] + span {
			margin-left: 1px;
		}
		.el-table__row {
			td {
				border: none !important;
				height: 55px;
				cursor: pointer;
			}
		}
	}
}
.ztbox {
	display: flex;
	align-items: center;
	justify-content: center;
	.dian {
		margin-right: 8px;
		width: 7px;
		height: 7px;
		border-radius: 50%;
	}
}
.czan {
	display: flex;
	justify-content: center;
}
#printDivdyAll {
	margin-top: -23px;
	width: 1000px;
	height: 400px;
	padding: 5px;

	td {
		text-align: center;
		font-size: 18px;
	}

	.zhai {
		height: 60px;
	}

	.shense {
		font-size: 20px;
	}

	table {
		width: 100%;
		height: 100%;
	}
}
.zBox {
	height: 99.8%;
	background-color: #ffffff;
	border-radius: 10px;
	padding: 20px;
}
:deep(.shbj) {
	background: url(../../assets/images/spbj.png) no-repeat;
	color: #be1a21;
	width: 140px;
	background-size: 100% 100%;
	padding: 5px 15px;
	font-size: 14px;
	margin-bottom: 10px;
	font-weight: 600;
}
.sptop {
	margin-top: 20px;
}
:deep(.bz) {
	.el-form-item__label {
		width: 50px !important;
	}
}
.red {
	color: #ff0000;
}
.spzt {
	width: 20px;
	height: 20px;
	display: inline-block;
	background-size: contain;
	margin-right: 10px;
}
.jdbox {
	position: relative;
}
.jdbox:last-child .xuLine {
	display: none;
}
.xuLine {
	position: absolute;
	width: 1px;
	height: 17px;
	border-left: 2px dashed rgb(204, 204, 204);
	left: 9px;
	top: 20px;
}
.dkJl {
	// display: flex;
	// flex-flow: row;
	// flex-wrap: wrap;
}
.li2Height {
	line-height: 30px;
}
.ytg {
	background: url(../../assets/images/mainImg/ok.png);
	background-size: 100% 100%;
}
.dsh {
	background: url(../../assets/images/mainImg/dsh.png);
	background-size: 100% 100%;
}
.btg {
	background: url(../../assets/images/mainImg/btg.png);
	background-size: 100% 100%;
}
</style>
